﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using MensUnoShop.Models;
using MensUnoShop.Models.ViewModels;
using MensUnoShop.Areas.Admin.Models;

namespace MensUnoShop.Areas.Admin.Filters
{
    /// <summary>
    /// 必須登入才能使用的頁面
    /// 以Session是否存在為依據
    /// 如果Session遺失會去Cookie檢查
    /// </summary>
    public class ManagerCheckFilter:ActionFilterAttribute
    {
        private HttpContext _httpcontext = HttpContext.Current;
        //驗證是否有登入
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Manager m;
            if (CheckManager(out m))
            {
                base.OnActionExecuting(filterContext);
                filterContext.Controller.ViewData["manager"] = m;
            }
            else
            {
                filterContext.Result = new RedirectResult("/admin/default/login?returnUrl="+HttpUtility.UrlEncode(_httpcontext.Request.RawUrl));
            }
            
        }

        private bool CheckManager(out Manager im)
        {
            im = null;
            bool ismember = true;
            try
            {
                //檢查Session中有沒有Member
                if (_httpcontext.Session["ma"] != null)
                    im = (Manager)_httpcontext.Session["ma"];
                else
                    ismember = false;
            }
            catch
            {
                im = null;
                ismember = false;
            }
            return ismember;
        }
        
    }
}